<?php 
class ControllerAccountMapping extends Controller {
	private $error = array();
	
	public function index() {
		if ($this->customer->isLogged()) {
			$this->redirect($this->url->http('account/account', '', 'SSL'));
    	} else {
			unset($this->session->data['account_mapping']);
			$this->redirect($this->url->http('account/login', '', 'SSL'));
		}
  	}
	private function generate_password($number) {
		$arr = array('a','b','c','d','e','f',
						'g','h','i','j','k','l',
						'm','n','o','p','r','s',
						't','u','v','x','y','z',
						'A','B','C','D','E','F',
						'G','H','I','J','K','L',
						'M','N','O','P','R','S',
						'T','U','V','X','Y','Z',
						'1','2','3','4','5','6',
						'7','8','9','0');
		// Auto Create Password
		$pass = "";
		for($i = 0; $i < $number; $i++) {
			$index = rand(0, count($arr) - 1);
			$pass .= $arr[$index];
		}

		return $pass;
	}
  	public function create() {
		//print_r($this->session->data['account_mapping']);
		if ($this->customer->isLogged()) {
			$this->redirect($this->url->http('account/account', '', 'SSL'));
    	}
		
		// Third-Party Identity Not Exist
		if (!isset($this->session->data['account_mapping'])) {
			$this->redirect($this->url->http('account/mapping', '', 'SSL'));
		}
		
    	$this->language->load('account/register');
    	$this->language->load('account/provider');
		
		$this->document->title = $this->language->get('heading_title');
		
		$this->load->model('account/customer');
		$this->load->model('account/mapping');
		
		// Third-Party Identity Exist => Auto Login
		$identity = $this->session->data['account_mapping']['identity'];
		
		$valid = $this->model_account_mapping->validIdentity($identity);
		
		if ($valid) {
			$customer = $this->model_account_customer->getCustomer($valid['customer_id']);
			//print_r($customer);
			if (is_array($customer) && !empty($customer)) {
				$this->customer->login($customer['username'], '');
				$this->redirect($this->url->http('account/account'));
			} else {
				$this->model_account_mapping->deleteIdentity($identity);
			}
		}
		
				if ($this->validateRegister()) {
					unset($this->session->data['guest']);
					$pass = $this->generate_password(10);
					$addnew = array(
						'shop_id' => NULL,
						'firstname' => $this->session->data['account_mapping']['firstname'],
						'lastname' => $this->session->data['account_mapping']['lastname'],
						'email' => $this->session->data['account_mapping']['email'],
						'identity' => $this->session->data['account_mapping']['identity'],
						'provider' => $this->session->data['account_mapping']['provider'],
						'telephone' => '',
						'fax' => '',
						'cart' => NULL,
						'company' => '',
						'newsletter' => 1,
						'address_1' => '',
						'address_2' => '',
						'postcode' => '',
						'city' => '',
						'country_id' => 320,
						'zone_id' => 3756,
						'ym' => '',
						'skype' => '',
						'username' => $this->session->data['account_mapping']['firstname'].$this->session->data['account_mapping']['lastname'],
						'customer_group_id' => $this->config->get('config_customer_group_id'),
						'password' => $pass
					);
					
					$this->model_account_customer->addCustomer($addnew);
					$this->customer->login($this->session->data['account_mapping']['firstname'].$this->session->data['account_mapping']['lastname'], $pass);
					/*$this->model_account_customer->addCustomer($this->request->post);

					$this->customer->login($this->request->post['email'], $this->request->post['password']);*/
					/*$data = array();
					$data['customer_id'] = $customer_id;
					$data['identity'] 	= $this->session->data['account_mapping']['identity'];
					$data['provider'] 	= $this->session->data['account_mapping']['provider'];
					$this->model_account_mapping->addIdentity($data);*/
					unset($this->session->data['account_mapping']);
				  
					$this->redirect($this->url->http('account/success'));
				} 
		
      	$this->data['breadcrumbs'] = array();

      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_home'),
			'href'      => $this->url->http('common/home'),
        	'separator' => false
      	);
		
      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_account'),
			'href'      => $this->url->http('account/account'),
        	'separator' => $this->language->get('text_separator')
      	);

      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->language->get('text_mapping'),
			'href'      => $this->url->http('account/mapping/create'),
        	'separator' => $this->language->get('text_separator')
      	);
				
		$this->children = array(
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'
		);

		$this->response->setOutput($this->render());
  	}
	
	private function validateLogin() {
    	if (!$this->customer->login($this->request->post['login_email'], $this->request->post['login_password'])) {
      		$this->error['warning'] = $this->language->get('error_login');
    	}

    	if (!$this->error) {
      		return true;
    	} else {
      		return false;
    	}
  	}
	
	private function validateRegister() {
    	if (!$this->error) {
      		return true;
    	} else {
      		return false;
    	}
  	}
	
	public function openid() {
		$this->load->model('account/mapping');
		
		if (empty($this->request->get['openid_mode'])) {
			
			if (!isset($this->request->get['openid']) || empty($this->request->get['openid'])) {
				$this->redirect($this->url->http('account/openid', '', 'SSL'));
			}
			
			if (isset($this->request->get['id'])) {
				$identity = strtolower($this->request->get['id']);
			} else {
				$identity = 'openid';
			}
			
			switch ($identity) {
				case 'flickr':
					$url = 'www.flickr.com/'.$this->request->get['openid'];
					break;
				case 'openid':
					$url = $this->request->get['openid'];
					break;
			}
			
			$openid_url = $this->model_account_mapping->formUrl($url);
			$openid_server_list = $this->model_account_mapping->getOpenIDServer($openid_url);
			
			if (empty($openid_server_list)) {
				$this->session->data['error'] = 'OpenID server is null!';
				$this->redirect($this->url->http('account/openid', '', 'SSL'));
			}
			
			if (!empty($openid_server_list[1])) {
				$openid_server = $openid_server_list[1];
			}
			
			if (!empty($openid_server_list[2])) {
				$openid_server = $openid_server_list[2];
			}

			$this->session->data['assoc_handle'] = $this->model_account_mapping->getAssociationHandle($openid_server);
			
			$data['openid.assoc_handle'] 	= $this->session->data['assoc_handle'];
			$data['openid.ax.mode'] 		= 'fetch_request';
			$data['openid.ax.required'] 	= 'attr1,attr2,attr3,attr4,attr5';
			$data['openid.ax.type.attr1'] 	= 'http://axschema.org/contact/email';
			$data['openid.ax.type.attr2'] 	= 'http://axschema.org/namePerson/first';
			$data['openid.ax.type.attr3'] 	= 'http://axschema.org/namePerson/last';
			$data['openid.ax.type.attr4'] 	= 'http://axschema.org/contact/country/home';
			$data['openid.ax.type.attr5'] 	= 'http://axschema.org/pref/language';
			$data['openid.claimed_id'] 		= $openid_url;
			$data['openid.identity'] 		= $openid_url;
			$data['openid.mode'] 			= 'checkid_setup';
			$data['openid.ns'] 				= 'http://specs.openid.net/auth/2.0';
			$data['openid.ns.ax'] 			= 'http://openid.net/srv/ax/1.0';
			$data['openid.ns.sreg'] 		= 'http://openid.net/extensions/sreg/1.1';
			$data['openid.realm'] 			= $this->url->http('common/home', '', 'SSL');
			$data['openid.return_to'] 		= $this->url->http('account/mapping/openid', '', 'SSL');
			$data['openid.sreg.optional'] 	= 'nickname,email,fullname,dob,gender,postcode,country,language,timezone';
			$data['openid.sreg.policy_url'] = $this->model_account_mapping->getPolicyUrl();
			$data['openid.sreg.required'] 	= 'email';
			$data['openid.trust_root'] 		= $this->url->http('common/home', '', 'SSL');
			
			$redirectURL = $openid_server . '?' . http_build_query($data);
			$this->redirect($redirectURL);
		} else {
			if ('id_res' == $this->request->get['openid_mode']) {
				if (isset($this->request->get['openid_identity'])) {
					$identity = $this->model_account_mapping->formUrl($this->request->get['openid_identity']);
				} else {
					$identity = $this->model_account_mapping->formUrl($this->request->get['openid_claimed_id']);
				}
				
				$this->session->data['account_mapping'] = array(
					'provider' => 'Google',
					'identity' => $identity,
					'email' => $this->request->get['openid_ax_value_email'],
					'auth' => true
				);
				
				unset($this->session->data['assoc_handle']);
				
				$this->redirect($this->url->http('account/openid/create', '', 'SSL'));
			} else {
				$this->session->data['error'] = 'Identity Error!!';
				$this->redirect($this->url->http('account/openid', '', 'SSL'));
			}
		}
	}
	
	public function google() {
		$this->load->model('account/mapping');
		
		if (!isset($this->request->get['openid_mode'])) {
			$openid_server = $this->model_account_mapping->getEndPoint('https://www.google.com/accounts/o8/id');
			$this->session->data['assoc_handle'] = $this->model_account_mapping->getAssociationHandle($openid_server);
			
			$data = array();
			$data['openid.ns'] 						= 'http://specs.openid.net/auth/2.0';
			$data['openid.claimed_id'] 				= 'http://specs.openid.net/auth/2.0/identifier_select';
			$data['openid.identity'] 				= 'http://specs.openid.net/auth/2.0/identifier_select';
			$data['openid.return_to'] 				= $this->url->http('account/mapping/google', '', 'SSL');
			$data['openid.realm'] 					= $this->url->http('common/home', '', 'SSL');
			$data['openid.assoc_handle'] 			= $this->session->data['assoc_handle'];
			$data['openid.mode'] 					= 'checkid_setup';
			$data['openid.ns.ext1'] 				= 'http://openid.net/srv/ax/1.0';
			$data['openid.ext1.mode'] 				= 'fetch_request';
			$data['openid.ext1.required'] 			= 'email,first,last';
			$data['openid.ext1.type.email'] 		= 'http://axschema.org/contact/email';
			$data['openid.ext1.type.first'] 		= 'http://axschema.org/namePerson/first';
			$data['openid.ext1.type.last'] 			= 'http://axschema.org/namePerson/last';
			$data['openid.ns.sreg'] 				= 'http://openid.net/extensions/sreg/1.1';
			$data['openid.sreg.required'] 			= 'email';
			$data['openid.sreg.optional'] 			= 'fullname,nickname,dob,gender,postcode,country,language,timezone';
			$data['openid.sreg.policy_url'] 		= $this->model_account_mapping->getPolicyUrl();

			$redirectURL = $openid_server . '?' . http_build_query($data);
			$this->redirect($redirectURL);
		} else {
			if (('id_res' == $this->request->get['openid_mode']) && ($this->session->data['assoc_handle'] == $this->request->get['openid_assoc_handle'])) {
				if (isset($this->request->get['openid_identity'])) {
					$identity = $this->model_account_mapping->formUrl($this->request->get['openid_identity']);
				} else {
					$identity = $this->model_account_mapping->formUrl($this->request->get['openid_claimed_id']);
				}
				
				$this->session->data['account_mapping'] = array(
					'provider' => 'Google',
					'identity' => $identity,
					'email' => $this->request->get['openid_ext1_value_email'],
					'firstname' => $this->request->get['openid_ext1_value_first'],
					'lastname' => $this->request->get['openid_ext1_value_last'],
					'auth' => true
				);
				
				unset($this->session->data['assoc_handle']);
				
				$this->redirect($this->url->http('account/mapping/create', '', 'SSL'));
			} else {
				$this->session->data['error'] = 'Identity Error!!';
				
				$this->redirect($this->url->http('account/mapping', '', 'SSL'));
			}
		}
  	}
	
	public function yahoo() {
		$this->load->model('account/mapping');
		
		if (empty($this->session->data['assoc_handle']) && empty($this->request->get['openid_mode'])) {
			$openid_server = 'https://open.login.yahooapis.com/openid/op/auth';
			$this->session->data['assoc_handle'] = $this->model_account_mapping->getAssociationHandle($openid_server);
			
			$data = array();
			$data['openid.ns'] 						= 'http://specs.openid.net/auth/2.0';
			$data['openid.claimed_id'] 				= 'http://specs.openid.net/auth/2.0/identifier_select';
			$data['openid.identity'] 				= 'http://specs.openid.net/auth/2.0/identifier_select';
			$data['openid.return_to'] 				= $this->url->http('account/mapping/yahoo', '', 'SSL');
			$data['openid.realm'] 					= $this->url->http('common/home', '', 'SSL');
			$data['openid.assoc_handle'] 			= $this->session->data['assoc_handle'];
			$data['openid.mode'] 					= 'checkid_setup';
			$data['openid.ns.ax'] 					= 'http://openid.net/srv/ax/1.0';
			$data['openid.ax.mode'] 				= 'fetch_request';
			$data['openid.ax.required'] 			= 'email,firstname,lastname,country,language';
			$data['openid.ax.type.email'] 			= 'http://axschema.org/contact/email';
			$data['openid.ax.type.first'] 			= 'http://axschema.org/namePerson';
			$data['openid.ax.type.last'] 			= 'http://axschema.org/namePerson';
			$data['openid.ns.sreg'] 				= urlencode('http://openid.net/extensions/sreg/1.1');
			$data['openid.sreg.required'] 			= 'email';
			$data['openid.sreg.optional'] 			= 'fullname,nickname,dob,gender,postcode,country,language,timezone';
			$data['openid.sreg.policy_url'] 		= $this->model_account_mapping->getPolicyUrl();
			$data['openid.trust_root'] 				= HTTPS_SERVER;
			
			$redirectURL = $openid_server . '?' . http_build_query($data);
			$this->redirect($redirectURL);
		} else {
			if ('id_res' == $this->request->get['openid_mode'] && $this->session->data['assoc_handle'] == $this->request->get['openid_assoc_handle']) {
				if (isset($this->request->get['openid_identity'])) {
					$identity = $this->model_account_mapping->formUrl($this->request->get['openid_identity']);
				} else {
					$identity = $this->model_account_mapping->formUrl($this->request->get['openid_claimed_id']);
				}
				
				$this->session->data['account_mapping'] = array(
					'provider' => 'Yahoo',
					'identity' => $identity,
					'email' => $this->request->get['openid_ax_value_email'],
					'firstname' => $this->request->get['openid_ax_value_email'],
					'lastname' => '',
					'auth' => true
				);
				
				unset($this->session->data['assoc_handle']);
				
				$this->redirect($this->url->http('account/mapping/create', '', 'SSL'));
			} else {
				$this->session->data['error'] = 'Identity Error!!';
				
				$this->redirect($this->url->http('account/mapping', '', 'SSL'));
			}
		}
	}
	
	public function msn() {
		$this->config->set('config_error_display', 0);
		$this->load->model('account/mapping');
		
		$settingsFile	= HTTPS_SERVER . 'system/library/windows_live/Application-Key.xml';
		$debug			= true;
		$cookie_name	= 'webauthtoken';
		$cookie_time	= time() + (10 * 365 * 24 * 60 * 60);
		//add AppId
		$appid 			= '';//if config in cpanel: $this->config->get('live_app_id');
		//add Secret
		$secret 		= '';//if config in cpanel: $this->config->get('live_app_secret');
		
		if ($appid == '' || $secret == '') {
			$this->session->data['error'] = 'Service Disable!!';
			$this->redirect($this->url->http('account/mapping', '', 'SSL'));
		}
		
		include_once DIR_SYSTEM . '/library/windows_live/windowslivelogin.php';
		
		$wll = WindowsLiveLogin::initFromXml($settingsFile);
		$wll->setDebug($debug);
		$wll->setAppId($appid);
		$wll->setSecret($secret);
		$wll->setPolicyUrl($this->model_account_mapping->getPolicyUrl());
		$wll->setReturnUrl($this->url->http('account/mapping/msn', '', 'SSL'));
		
		$user = $wll->processConsent($_REQUEST);
		if(!empty($user)){
			setcookie($cookie_name, $user->getToken(), $cookie_time);
		}
		
		$token = $_COOKIE[$cookie_name];
		
		if ($token) {
			$user = $wll->processConsentToken($token);
			if (!$user->isValid()) {
				setcookie($cookie_name);
				$this->session->data['error'] = 'Identity Error!!';
				$LocationUrl = $this->url->http('account/mapping/msn', '', 'SSL');
				$this->redirect($LocationUrl);
			} else {
				$url = 'https://livecontacts.services.live.com/users/@L@'.$user->getLocationID().'/rest/livecontacts/owner';
				$owner = $this->getLiveID($url, array('Authorization: DelegatedToken dt="'.$user->getDelegationToken().'"'));
				$identity = 'http://cid-'.$user->getLocationID().'.profile.live.com/';
				$email = (string)$owner->WindowsLiveID;
				$firstname = $owner->Profiles->Personal->LastName;
				$lastname = $owner->Profiles->Personal->FirstName;
				
				$this->session->data['account_mapping'] = array(
					'provider' => 'Windows Live',
					'identity' => $identity,
					'email' => $email,
					'firstname' => $firstname,
					'lastname' => $lastname,
					'auth' => true
				);
				
				$this->redirect($this->url->http('account/mapping/create', '', 'SSL'));
			}
		} else {
			$LocationUrl = $wll->getConsentUrl('Contacts.View');
			$this->redirect($LocationUrl);
		}
	}
	
	private function getLiveID($url, $header) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($curl, CURLOPT_TIMEOUT, 60);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		
		$contents = curl_exec($curl);
		curl_close($curl);
		
		try {
			$xml = new SimpleXMLElement($contents);
		} catch(Exception $e) {
			return false;
		}
		return $xml;
	}
	
	public function facebook() {
		$this->config->set('config_error_display', 0);
		require_once DIR_SYSTEM . '/library/facebook/facebook.php';
		
		$facebook = new Facebook(array(
			//add AppId
			'appId'  => '',//if config in cpanel: $this->config->get('facebook_app_id'),
			//add Secret
			'secret' => ''//if config in cpanel: $this->config->get('facebook_app_secret')
		));
		
		// Get User ID
		$fb_user = $facebook->getUser();
	
		if ($fb_user) {

			try {
				// Proceed knowing you have a logged in user who's authenticated.
				$fb_user_profile = $facebook->api('/me');
			} catch (FacebookApiException $e) {
				//error_log($e);
				$fb_user = null;
			}
			
			$permissions = $facebook->api('/me/permissions');
			
			if (!array_key_exists('email', $permissions['data'][0]) ) {
				$this->redirect(HTTP_SERVER.'system/library/facebook/getUser.php');
			}
			
			$fb_user_profile = $facebook->api('/me');
			
			if ($fb_user_profile){
				$this->session->data['account_mapping'] = array(
					'provider' => 'Facebook',
					'identity' => $fb_user_profile['id'],
					'email' => $fb_user_profile['email'],
					'firstname' => $fb_user_profile['name'],
					'lastname' =>'',
					'auth' => true
				);
				
				$this->redirect($this->url->http('account/mapping/create'));
			} else {
				$this->session->data['error'] = 'Identity Error!!';
				
				$this->redirect($this->url->http('account/mapping'));
			}
			
		} else {
			header('Location: '.HTTP_SERVER.'system/library/facebook/getUser.php');
			//header('Location: '.$facebook->getLoginUrl(array('scope' => 'email')));
		}
	}
	

}
?>